#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FIFO_FILE "fifo"

class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path += '/' + name;
        umask(0);
        // 创建管道
        int n = mkfifo(_fifoname.c_str(), 0664);
        if (n < 0) // 创建失败
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }
    ~NamedFifo()
    {
        // 删除管道
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "remove fifo success" << std::endl;
        }
        else
        {
            std::cerr << "remove fifo failed" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FifoOper
{
public:
    FifoOper(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path += '/' + name;
    }
    void OpenForRead()
    {
        // 打开管道文件，wirte方没有执行open的时候，read方就要阻塞在open进程内部等待
        // 直到管道被打开，open才返回
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << " open fifo error" << std::endl;
            return;
        }
        std::cout << " open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void Read()
    {
        // read
        while (true)
        {
            char buffer[1024];
            int num = read(_fd, buffer, sizeof(buffer) - 1);
            if (num > 0)
            {
                std::cout << "Client say#" << buffer << std::endl;
            }
            else if (num == 0)
            {
                std::cout << "Client quit, me too" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read error" << std::endl;
                break;
            }
        }
    }
    void Write()
    {
        // 写入操作
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        while (true)
        {
            std::cout << "Please Enter#";
            getline(std::cin, message);
            message += ",message" + std::to_string(cnt++) + "[" + std::to_string(id) + "]";
            // 写入
            write(_fd, message.c_str(), message.size());
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }

    ~FifoOper() {}

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};
